package com.example.test17_2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    CurrentTimeService cts;//继承Binder类绑定服务使用参数
    Messenger messenger;
    boolean bound;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, CurrentTimeService.class);
                bindService(intent, sc, BIND_AUTO_CREATE);//绑定服务
                if (bound) {//如果绑定则显示当前时间
//                    Toast.makeText(MainActivity.this, cts.getCurrentTime(),
//                            Toast.LENGTH_LONG).show();
                    Message message = Message.obtain(null,CurrentTimeService.CURRENT_TIME,0,0);
                    try{
                        messenger.send(message);
                    }catch (RemoteException e ){
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (bound) {
            bound = false;
            unbindService(sc);//解绑定
        }
    }

    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//            CurrentTimeService.LocalBinder binder = (CurrentTimeService.LocalBinder) iBinder;//获得自定义的LocalBinder对象
//            cts = binder.getService();//获得CurrentTimeService对象
            messenger = new Messenger(iBinder);
            bound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            bound = false;
            messenger = null;
        }
    };
}